import React from 'react';

import Select from './Select';

export type OptionValues = string | number | boolean;

interface ISelectedData {
  // value?: OptionValues | OptionValues [] | string[] | number | number[] | boolean;
  value?: OptionValues; // 作为key 来使用 string
  label?: string;
}

interface IProps {
  titles?: ISelectedData[];
  defaultValues?: ISelectedData[];
  loadData?: (depth: number, id?: string) => Promise<ISelectedData[]>; // 加载数据的方法
  onSelect?: (values: ISelectedData[]) => void; // 选中后返回数据
}

export default class GangedSelect extends React.Component<IProps, any> {
  public static defaultProps = {
    titles: [{ value: '0', label: '省份' }, { value: '0-0', label: '城市' }],
  };

  constructor(props: IProps) {
    super(props);
    this.state = {
      values: props.defaultValues || props.titles || [],
      options: [[], [], []],
    };
    this.onChange = this.onChange.bind(this);
    this.onFocus = this.onFocus.bind(this);
  }

  public onChange(option: ISelectedData | ISelectedData[] | null, index: number) {
    if (option && option instanceof Array) {
      if (this.props.onSelect) {
        this.props.onSelect(this.state.values);
      }
      return;
    }

    if (option && option.label && this.state.values[index].value === option.value) {
      if (this.props.onSelect) {
        this.props.onSelect(this.state.values);
      }
      return;
    }
    const initValues = this.props.titles || [];
    let mapValues = [...initValues];
    switch (index) {
      case 0:
        mapValues = [...initValues];
        mapValues[index] = option || {};
        break;
      case 1:
        mapValues = [...this.state.values];
        mapValues[index] = option || {};
        if (mapValues[2]) {
          mapValues[2] = initValues[2];
        }
        break;
      case 2:
        mapValues = [...this.state.values];
        mapValues[index] = option || {};
        break;
    }
    // 选择的数据保存到上级
    if (this.props.onSelect) {
      this.props.onSelect(mapValues);
    }
    this.setState({
      values: mapValues,
    });
  }

  public onFocus(event: any, index: number) {
    // todo 优化 每次点击都会重新获取
    // 第一级直接获取可选择的数据
    if (index === 0 && this.props.loadData) {
      this.props.loadData(index)
        .then((data) => {
          const mapOptions = [...this.state.options];
          mapOptions[index] = data;
          this.setState({
            options: mapOptions,
          });

        }).catch((e) => {
          console.log('级联获取数据失败', e);
        });
    } else if (this.props.loadData) {
      if (!this.state.values[index - 1].value) {
        return;
      }
      const initValues = this.props.titles || [];
      // 前一项的值跟默认值相同时候 不给予选者
      if (initValues.length && this.state.values[index - 1].value === initValues[index - 1].value) {
        return;
      }
      const value = this.state.values[index - 1] && this.state.values[index - 1].value;
      this.props.loadData(index, value).then((data) => {
        const mapOptions = [...this.state.options];
        mapOptions[index] = data;
        this.setState({
          options: mapOptions,
        });

      }).catch((e) => {
        console.log('级联获取数据失败', e);
      });
    }
  }

  public render() {
    const props = this.props;
    const depth = props.titles && props.titles.length || 0;
    return (
      <div className="bricks-ganged-select">
        {
          props.titles && props.titles.map((item, index) => {
            const className = `depth-${depth} select${index}`;
            return <div className={className} key={item.label}>
              <Select
                value={this.state.values[index]}
                options={this.state.options[index]}
                onChange={(selectedOption) => this.onChange(selectedOption, index)}
                onFocus={(event) => this.onFocus(event, index)}
              />
            </div>;
          })
        }
      </div>
    );
  }
}
